onMsg = (msg, sender, sendResponse)->
  console.log(msg)
  if msg.type is "addDownload"
    window.addDownload(msg.val)
    chrome.runtime.onMessage.removeListener(onMsg)
    onMsg = null
  return
chrome.runtime.onMessage.addListener(onMsg)


$(document).ready(->
  filenameField = $("#filenameField")
  urlField = $("#urlField")
  sizeField = $("#sizeField")

  $("#cancelBtn").click(->
    chrome.windows.getCurrent((window)->
      chrome.windows.remove(window.id)
      return
    )
    return
  )



  window.addDownload = (downInfo)->
    document.title = "Aria2[#{downInfo.filename}]"
    filenameField.val(downInfo.filename)
    urlField.val(downInfo.url)
    sizeField.val(Utils.getFileLength(downInfo.fileSize))

    $("#startBtn").click(
      ->
        downInfo.url = urlField.val()
        downInfo.filename = filenameField.val()
        Utils.fillCookies(downInfo,->
          chrome.runtime.sendMessage({
            type :"directDownload"
            val : downInfo
          })
          chrome.windows.getCurrent((window)->
            chrome.windows.remove(window.id)
            return
          )
        )
        return
    )
    return
)